package com.example.demo.service;

import com.example.demo.mapper.OrderMapper;
import com.example.demo.model.Coffee;
import com.example.demo.model.Order;
import com.example.demo.model.OrderState;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;


@Slf4j
@Service
@Transactional
public class CoffeeOrderService {
    @Autowired
    private OrderMapper orderMapper;

    public Order createOrder(String customer, Coffee coffee) {
        Order order = Order.builder()
                .customer(customer)
                .coffeeid(coffee.getId())
                .state(OrderState.INIT.toString())
                .build();
        int saved = orderMapper.save(order);
        ArrayList<Order> orders = orderMapper.findByCustomer(customer);
        log.info("New Order: {}", orders);
        order = null;
        for(Order o: orders){
            if (coffee.getName() == o.getName()){
                order = o;
            }
        }
        return order;
    }

    public boolean updateState(Order order, OrderState state) {
        if (state.toString().compareTo(order.getState()) == 0) {
            log.warn("Wrong State order: {}, {}", state, order.getState());
            return false;
        }
        order.setState(state.toString());
        orderMapper.update(order);
        log.info("Updated Order state: {}", order);
        return true;
    }
}
